package kr.ac.pusan.cse.hts.server;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import kr.ac.pusan.cse.hts.common.data.*;
import kr.ac.pusan.cse.hts.common.network.NetworkController;
import kr.ac.pusan.cse.hts.common.network.NetworkControllerJMSImpl;
import kr.ac.pusan.cse.hts.common.network.ReceiveListener;

public class OrderController implements ReceiveListener {
	private NetworkController nc;
	private List<BuySellOrder> proceeded;
	private BuySellOrderComparator cmp;
	public OrderController(){
		nc = new NetworkControllerJMSImpl("","server","client");
		nc.addListener(BuySellOrder.class, this);
		proceeded = new ArrayList<BuySellOrder>();
		cmp = new BuySellOrderComparator();
	}
	public OrderController(String name){
		nc = new NetworkControllerJMSImpl(name,"server","client");
		nc.addListener(BuySellOrder.class, this);
		proceeded = new ArrayList<BuySellOrder>();
		cmp = new BuySellOrderComparator();
	}
	public void received(Object message) {
		System.out.println("wow! in server");
		BuySellOrder order = (BuySellOrder) message;
		OrderType type = order.getType();
		if(type == OrderType.NORMAL_BUY){
			placeNormalBuyOrder(order);
		}else if(type == OrderType.NORMAL_SELL){
			placeNormalSellOrder(order);
		}else if(type == OrderType.RESERVED_BUY){
			placeReservedBuyOrder(order);
		}else if(type == OrderType.RESERVED_SELL){
			placeReservedSellOrder(order);
		}else{
			//
		}
		nc.send(new OKResult(order));
	}
	private void placeReservedSellOrder(BuySellOrder order) {
		// TODO Auto-generated method stub
		
	}
	private void placeReservedBuyOrder(BuySellOrder order) {
		// TODO Auto-generated method stub
		
	}
	private void placeNormalSellOrder(BuySellOrder order) {
		proceeded.add(order);		
	}
	private void placeNormalBuyOrder(BuySellOrder order){
		order.setDate();
		List<BuySellOrder> list = new ArrayList<BuySellOrder>();
		for(BuySellOrder placedOrder : proceeded){
			String name = order.getName();
			if(placedOrder.getName().equals(name))
				list.add(placedOrder);
		}
		java.util.Collections.sort(list, cmp);
		proceeded.add(order);
	}
}
class BuySellOrderComparator implements Comparator<BuySellOrder> {
	public int compare(BuySellOrder o1, BuySellOrder o2) {
		if(o1.getPrice()>o1.getPrice())
			return 1;
		else if(o1.getPrice()<o1.getPrice())
			return -1;
		else{
			return o1.getDate().compareTo(o2.getDate());
		}
	}
}